package handler

import (
	"encoding/json"
	"sep24-repo/cache"
	"sep24-repo/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	author := c.PostForm("author")

	order := model.Order{
		Name:   name,
		Author: author,
	}
	err := model.DB.Create(&order).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "order_add_" + strconv.Itoa(int(order.ID))
	var orders model.Order
	model.DB.Where("id=?", order.ID).First(&orders)
	jsonData, _ := json.Marshal(orders)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
		"data": order,
	})
	return
}

func StyleAdd(c *gin.Context) {
	style_name := c.PostForm("style_name")
	order_id, _ := strconv.Atoi(c.PostForm("order_id"))

	style := model.Style{
		OrderId:   order_id,
		StyleName: style_name,
	}
	err := model.DB.Create(&style).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func StyleList(c *gin.Context) {
	var style []model.Style

	/*
		select
		orders.author,
		orders.`name`,
		styles.style_name
		from styles
		left join orders on styles.order_id = orders.id
	*/

	err := model.DB.Table("styles").
		Joins("left join orders on styles.order_id = orders.id").
		Find(&style).
		Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "列表获取失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": style,
	})
	return
}

func List(c *gin.Context) {
	var style []model.Style

	redis_key := "style_list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&style)
		jsonData, _ := json.Marshal(style)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &style)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": style,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var order model.Order

	redis_key := "order_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"data": order,
	})
	return
}
